/**
 * 用户服务
 * 提供用户相关的业务逻辑
 */
const jwt = require('jsonwebtoken')
const { User } = require('../models')
const authConfig = require('../config/auth')
const CustomException = require('../utils/customException')
const ResultCodeEnum = require('../utils/resultCodeEnum')
const HttpRequest = require('../utils/httpRequest')
const config = require('../config/config')
// 获取随机字符串
function getUUid() {
	return Math.random().toString(36).substring(2, 10)
}

class UserService {
	/**
	 * 用户登录
	 * @param {string} username - 用户名
	 * @param {string} password - 密码
	 * @returns {Promise<Object>} 包含用户信息和token的对象
	 * @throws {CustomException} 如果登录失败
	 */
	async login(username, password) {
		// 查找用户
		const user = await User.findOne({ where: { username } })

		if (!user) {
			throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR)
		}

		// 验证密码
		const isPasswordValid = await user.validatePassword(password)

		if (!isPasswordValid) {
			throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR)
		}

		// 生成JWT token
		const token = jwt.sign({ id: user.id }, authConfig.jwt.secret, { expiresIn: authConfig.jwt.expiresIn })

		// 返回用户信息和token
		return {
			user: {
				id: user.id,
				username: user.username,
				phone: user.phone,
				registerTime: user.register_time
			},
			token
		}
	}

	/**
	 * 用户注册
	 * @param {Object} userData - 用户数据
	 * @returns {Promise<Object>} 创建的用户对象
	 * @throws {CustomException} 如果注册失败
	 */
	async register(userData) {
		// 检查用户名是否已存在
		const existingUser = await User.findOne({ where: { username: userData.username } })

		if (existingUser) {
			throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR)
		}

		// 创建新用户
		const user = await User.create({
			username: userData.username,
			password: userData.password,
			phone: userData.phone,
			register_time: new Date(),
			role: 'normal'
		})

		// 生成JWT token
		const token = jwt.sign({ id: user.id }, authConfig.jwt.secret, { expiresIn: authConfig.jwt.expiresIn })

		// 返回用户信息和token
		return {
			user: {
				id: user.id,
				username: user.username,
				phone: user.phone,
				registerTime: user.register_time
			},
			token
		}
	}

	/**
	 * 获取用户信息
	 * @param {number} userId - 用户ID
	 * @returns {Promise<Object>} 用户信息
	 * @throws {CustomException} 如果用户不存在
	 */
	async getUserInfo(userId) {
		const user = await User.findByPk(userId)

		if (!user) {
			throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR)
		}

		return {
			id: user.id,
			username: user.username,
			phone: user.phone,
			registerTime: user.register_time
		}
	}

	/**
	 * 微信小程序登录
	 * @param {string} code - 微信小程序登录code
	 * @returns {Promise<Object>} 包含用户信息和token的对象
	 * @throws {CustomException} 如果登录失败
	 */
	async wxLogin(code) {
		if (!code) {
			throw new CustomException(ResultCodeEnum.PARAM_ERROR, 'code不能为空')
		}

		try {
			// 调用微信官方接口获取openid
			const wxAppId = config.WX_APPID || 'your_wx_appid'
			const wxSecret = config.WX_SECRET || 'your_wx_secret'
			const wxLoginUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxAppId}&secret=${wxSecret}&js_code=${code}&grant_type=authorization_code`
			const response = await HttpRequest.get(wxLoginUrl)
			console.log('response==>', response)

			if (response.errcode) {
				throw new CustomException(ResultCodeEnum.SYSTEM_ERROR, `微信登录失败: ${response.errmsg}`)
			}

			const { openid } = response
			console.log('openid==>', openid)

			// 根据openid查找用户
			let user = await User.findOne({ where: { openid } })

			// 如果用户不存在，则创建新用户
			if (!user) {
				console.log('user==>', user)

				user = await User.create({
					username: `布丁_${getUUid()}`,
					password: '000000',
					phone: '13911111111',
					openid,
					register_time: new Date(),
					role: 'normal'
				})
			}

			// 生成JWT token
			const token = jwt.sign({ id: user.id }, authConfig.jwt.secret, { expiresIn: authConfig.jwt.expiresIn })

			// 返回用户信息和token
			return {
				user: {
					id: user.id,
					username: user.username,
					phone: user.phone,
					registerTime: user.register_time
				},
				token
			}
		} catch (error) {
			if (error instanceof CustomException) {
				throw error
			}
			throw new CustomException(ResultCodeEnum.SYSTEM_ERROR, `微信登录失败: ${error.message}`)
		}
	}
}

module.exports = new UserService()
